import time
from io import BytesIO
import pytesseract
from PIL import Image

from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from Utils import ShoppingDriver

# 配置Tesseract路径（根据实际情况修改）
pytesseract.pytesseract.tesseract_cmd = r'D:\Program Files\Tesseract-OCR\tesseract.exe'

#用户名、密码、验证码、同意协议的选择器
username="body > div.body-content-container > div.body-content-formal-container > div.am-g.user-register-container.theme-data-edit-event > div > div > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div:nth-child(1) > input"
password="body > div.body-content-container > div.body-content-formal-container > div.am-g.user-register-container.theme-data-edit-event > div > div > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div:nth-child(2) > input"
verify_code="body > div.body-content-container > div.body-content-formal-container > div.am-g.user-register-container.theme-data-edit-event > div > div > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div:nth-child(3) > input"
agree_text="body > div.body-content-container > div.body-content-formal-container > div.am-g.user-register-container.theme-data-edit-event > div > div > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div.agreement.am-margin-top-main > label > span"

class ShoppingRegister:
   url=""
   driver=""
def __init__(self):
    self.driver=ShoppingDriver.driver
    self.url="http://8.155.1.153/?s=user/reginfo.html"
    self.driver.get(self.url)
    self.driver.fullscreen_window()

def getverifycode(self):
    try:
        # 定位元素
        element = self.driver.find_element(By.CSS_SELECTOR, "#form-verify-img")
        # 截图验证码的元素(Selenium 自带方法,直接对元素截图，比全图截图精准)
        img_bytes = element.screenshot_as_png
        img_element = Image.open(BytesIO(img_bytes))
        # 用OCR工具识别图片
        # 预处理：转为灰度图
        img_element = img_element.convert("L")
        # OCR 识别（限制识别范围：只识别数字）
        img_text = pytesseract.image_to_string(
            img_element,
            config="--psm 10 -c tessedit_char_whitelist=0123456789"
        )
        # 清洗结果（去掉空白、换行符）
        img_text = img_text.strip()
        return img_text
    except Exception as e:
        print("getverifycode failed")
        print(e)
        # 添加截图
        ShoppingDriver.getScreeShot()
        raise

def RegisterSuccess(self):
    try:
        self.driver.find_element(By.CSS_SELECTOR, username).clear()
        self.driver.find_element(By.CSS_SELECTOR, password).clear()
        self.driver.find_element(By.CSS_SELECTOR, verify_code).clear()
        # 输入框输入账号
        self.driver.find_element(By.CSS_SELECTOR, username).send_keys("xiaohua")
        # 输入框输入密码
        self.driver.find_element(By.CSS_SELECTOR, password).send_keys("bite123")
        # 输入框输入验证码
        # 获取验证码
        img_text = ShoppingRegister.getverifycode(self)
        # 输入验证码
        self.driver.find_element(By.CSS_SELECTOR, verify_code).send_keys(img_text)
        # 点击同意协议
        (self.driver.find_element(By.CSS_SELECTOR, "body > div.body-content-container > div.body-content-formal-container > div.am-g.user-register-container.theme-data-edit-event > div > div > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div.agreement.am-margin-top-main > label > span")
         .click())
        # 点击注册
        (self.driver.find_element(By.CSS_SELECTOR,
        "body > div.body-content-container > div.body-content-formal-container > div.am-g.user-register-container.theme-data-edit-event > div > div > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div.am-form-group.am-margin-top-main.am-padding-0 > button")
         .click())
        time.sleep(3)
        # 注册成功后，验证网站logo，确认是不是进入了首页
        self.driver.find_element(By.CSS_SELECTOR,
        "body > div.body-content-container > div.body-content-formal-container > div.nav-seasrch.header-nav-simple.am-hide-sm-only > div > div.logo.theme-data-edit-event > a > img")
    except Exception as e:
        print("RegisterSuccess failed")
        print(e)
        # 添加截图
        ShoppingDriver.getScreeShot()
        raise

def RegisterFail(self):
    try:
        flag=False
        time.sleep(2)
        # 获取验证码
        img_text = ShoppingRegister.getverifycode(self)
        test_dic = [
            {"desc": "用户名长度<2字符注册", "username": "a", "password": "123456",
             "verify_code": img_text, "agree_text": True},
            {"desc": "用户名长度>18字符注册", "username": "a" * 19, "password": "123456",
             "verify_code": img_text, "agree_text": True},
            {"desc": "不写用户名注册", "username": "", "password": "123456",
             "verify_code": img_text, "agree_text": True},
            {"desc": "密码长度<6字符注册", "username": "test_user", "password": "123",
             "verify_code": img_text, "agree_text": True},
            {"desc": "密码长度>18字符注册", "username": "test_user", "password": "a" * 19,
             "verify_code": img_text, "agree_text": True},
            {"desc": "不写密码注册", "username": "test_user", "password": "",
             "verify_code": img_text, "agree_text": True},
            {"desc": "不写验证码注册", "username": "test_user", "password": "123456",
             "verify_code": "", "agree_text": True},
            {"desc": "错误的验证码注册", "username": "test_user", "password": "123456",
             "verify_code": "wrong", "agree_text": True},
            {"desc": "不点击同意协议注册", "username": "test_user", "password": "123456",
             "verify_code": img_text, "agree_text": False}
        ]

        for dic in test_dic:
            #print(f"执行测试用例: {dic['desc']}")

            # 清空输入框
            self.driver.find_element(By.CSS_SELECTOR, username).clear()
            self.driver.find_element(By.CSS_SELECTOR, password).clear()
            self.driver.find_element(By.CSS_SELECTOR, verify_code).clear()
            time.sleep(1)

            # 输入用户名
            if dic["username"]:
                self.driver.find_element(By.CSS_SELECTOR,username).send_keys(dic["username"])

            # 输入密码
            if dic["password"]:
                self.driver.find_element(By.CSS_SELECTOR, password).send_keys(dic["password"])

            # 输入验证码
            if dic["verify_code"]:
                self.driver.find_element(By.CSS_SELECTOR, verify_code).send_keys(dic["verify_code"])

            # 处理同意协议
            agree_checkbox = self.driver.find_element(By.CSS_SELECTOR, agree_text)
            # 第一次if：需要点击同意，同时按钮没有被点击
            # 第二次if：需要点击同意，但是按钮已经被点击，所以不需要再点击
            if dic["agree_text"] :
                if not flag:
                    agree_checkbox.click()
                    flag=True
                    #print("按钮没有被点击，才点的")
                #else:
                    #print("按钮已经点过了")

            #最后一次if：不需要点击，同时按钮已经被点击，那就再点击一下取消
            elif not dic["agree_text"] :
                if flag:
                    agree_checkbox.click()
                    #print("取消按钮")

            # 点击注册
            (self.driver.find_element(By.CSS_SELECTOR,
            "body > div.body-content-container > div.body-content-formal-container > div.am-g.user-register-container.theme-data-edit-event > div > div > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div.am-form-group.am-margin-top-main.am-padding-0 > button")
             .click())
            # 注册失败后，验证是不是还在注册界面
            self.driver.find_element(By.CSS_SELECTOR,"body > div.body-content-container > div.body-content-formal-container > div.nav-seasrch.header-nav-simple > div > p.login-title.am-fl.am-vertical-align-middle.am-margin-left-main")

    except Exception as e:
        print("RegisterFail failed")
        print(e)
        # 添加截图
        ShoppingDriver.getScreeShot()
        raise

